﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;

namespace MVVMFramework.StarterKit
{
    class AppSettings
    {
        /// <summary>
        /// Application name
        /// </summary>
        public const string ApplicationName = "MVVM Framework Starter Kit";

        static AppSettings()
        {

        }

        private AppSettings()
        {
            
        }

        public readonly static AppSettings Instance = new AppSettings();

        /// <summary>
        /// Gets the application path
        /// </summary>
        public string ApplicationPath
        {
            get
            {
                return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }
        }

        private readonly object appPathLock = new object();
        private string applicationPath;
        /// <summary>
        /// Gets the application data path
        /// </summary>
        public string ApplicationDataPath
        {
            get
            {
                if (string.IsNullOrEmpty(applicationPath))
                {
                    lock (appPathLock)
                    {
                        if (string.IsNullOrEmpty(applicationPath))
                        {
                            string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                            applicationPath = Path.Combine(dir, ApplicationName);
                            if (!Directory.Exists(applicationPath))
                                Directory.CreateDirectory(applicationPath);

                            setPathSecurity(applicationPath);
                        }
                    }
                }

                return applicationPath;
            }
        }

        /// <summary>
        /// Gets the log path
        /// </summary>
        public string LogPath
        {
            get
            {
                return Path.Combine(ApplicationDataPath, "Logs");
            }
        }

        /// <summary>
        /// Sets the path security
        /// </summary>
        /// <param name="path">The path.</param>
        private void setPathSecurity(string path)
        {
            DirectorySecurity dirSecurity = new DirectorySecurity();
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            dirSecurity.AddAccessRule(
                new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow));

            Directory.SetAccessControl(path, dirSecurity);
        }
    }
}
